package com.xing.config.shiro.filter;

import com.xing.common.HttpUtils;
import lombok.Data;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.Collections;

/**
 * Created by Bradish7Y on 2017/9/15.
 * 控制同一用户在线session数
 *
 * @deprecated 每次请求都要与redis交互
 */
@Data
@Deprecated
public class KickoutSessionControlFilter_Deprecated extends AccessControlFilter {

    @Resource
    private RedisTemplate<String, Serializable> redisTemplate;

    @Resource(name = "updateKickoutRedisScript")
    private RedisScript<Boolean> redisScript;

    private int maxSession;//最大在线session数
    private String kickoutUrl;//成功踢出后重定向url
    private boolean kickoutAfter = false;//踢出最新登录、后登录，默认踢出之前登录
    private int sessionExpire = 1800;
    private SessionManager sessionManager;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        if (!subject.isAuthenticated() && !subject.isRemembered()) {//未授权且非remember
            //如果没有登录，直接进行之后的流程
            return true;
        }

        Session session = subject.getSession();
        String username = (String) subject.getPrincipal();
        Serializable sessionId = session.getId();


        if (session.getAttribute("kickout") == null) {
            redisTemplate.execute(redisScript, Collections.singletonList(username), sessionId, sessionExpire);
        }

        Long size = redisTemplate.opsForList().size(username);

        //超出最大会话数，开始踢人
        while (size-- > maxSession) {
            Serializable kickoutSessionId = null;
            if (kickoutAfter) { //如果踢出后者
                kickoutSessionId = redisTemplate.opsForList().rightPop(username);
            } else { //否则踢出前者
                kickoutSessionId = redisTemplate.opsForList().leftPop(username);
            }
            try {
                Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
                if (kickoutSession != null) {
                    //设置会话的kickout属性表示踢出了
                    kickoutSession.setAttribute("kickout", true);
                }
            } catch (Exception e) {//ignore exception
            }
        }

        //如果被踢出了，直接退出，重定向到踢出后的地址
        if (session.getAttribute("kickout") != null) {
            //会话被踢出了
            try {
                subject.logout();
            } catch (Exception e) { //ignore
            }
            saveRequest(request);

            HttpServletRequest httpRequest = WebUtils.toHttp(request);
            if (HttpUtils.isAjax(httpRequest)) {
                HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
                httpServletResponse.sendError(401);
                return false;
            } else {
                WebUtils.issueRedirect(request, response, kickoutUrl);
                return false;
            }
        }

        return true;
    }


}
